<template>
  <div class="qa-add-page">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/qaT" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">发布问题</h5>
    </div>

    <!-- 表单 -->
    <div class="form-container">
      <div class="mb-3">
        <label class="form-label">选择学科</label>
        <select class="form-select" v-model="question.subject">
          <option v-for="dict in subjectDict" :key="dict.id" :value="dict.id">
            {{ dict.name }}
          </option>
        </select>
      </div>

      <div class="mb-3">
        <label class="form-label">问题描述</label>
        <textarea 
          class="form-control" 
          rows="5" 
          placeholder="请详细描述你的问题..."
          v-model="question.content"
        ></textarea>
      </div>

      <div class="mb-3">
        <label class="form-label">添加图片（选填）</label>
        <div class="d-flex align-items-center gap-2">
          <div
              v-if="question.image"
              class="image-preview"
          >
            <img :src="question.image" alt="预览图" class="img-fluid">
            <button
                type="button"
                class="btn-close"
                @click="removeImage"
            ></button>
          </div>
          <button
              v-else
              type="button"
              class="btn btn-outline-secondary"
              @click="selectImage"
          >
            <i class="bi bi-image"></i>
            <span v-if="isImageUploading">正在上传...</span>
            <span v-else>上传图片</span>
          </button>
        </div>
      </div>

      <button 
        type="button" 
        class="btn btn-primary w-100"
        @click="submitQuestion"
      >发布问题</button>
    </div>
  </div>
</template>

<script>
import {subjectParentTypeDict} from "@/router/dict";
import http from "@/router/http";
import router from "@/router";
export default {
  name: 'QaAddView',
  data() {
    return {
      question: {},
      subjectDict: [],
      impagePath : null
    }
  },
  mounted() {
      subjectParentTypeDict.forEach(item => {
          this.subjectDict.push({
            id: item.id,
            name: item.name
          })
        })
  },
  methods: {
    selectImage() {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*';
      input.onchange = async (e) => {
        const file = e.target.files[0];
        if (file) {
          const allowedFormats = ['image/jpeg', 'image/png', 'image/gif'];
          if (!allowedFormats.includes(file.type)) {
            alert('请选择正确的图片格式（支持 JPEG、PNG、GIF）');
            return;
          }
          // 设置图片上传加载状态为true，可用于显示加载提示（如显示一个旋转图标等）
          this.isImageUploading = true;
          try {
            const formData = new FormData();
            formData.append('file', file);
            const response = await http.post('/admin/upload/file?fileType=message', formData, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            });
            if (response.status === 200) {
              console.log('图片上传成功');
              const baseUrl = http.defaults.baseURL || "";
              this.question.image = baseUrl +"/uploadPath"+response.data;
              this.impagePath = response.data;
            } else {
              console.error('图片上传失败:', response.data.message);
            }
          } catch (error) {
            console.error('图片上传失败：', error);
          } finally {
            // 无论上传成功与否，都将加载状态设置为false，隐藏加载提示
            this.isImageUploading = false;
          }
        } else {
          alert('请选择有效的图片文件');
        }
      };
      input.click();
    },
    removeImage() {
      this.question.image = null
    },
    async submitQuestion() {
      if (!this.question.subject) {
        alert('请选择科目');
        return;
      }
      if (!this.question.content.trim()) {
        alert('请输入问题描述');
        return;
      }
      const submitButton = document.querySelector('btn.btn-primary.w-100');
      if (submitButton) {
        submitButton.disabled = true; // 直接设置按钮的disabled属性为true，使其置灰不可点击
      }
      // 此处可添加提交问题时的整体加载状态处理，示例中暂略，可参考图片上传的加载状态逻辑自行添加
      try {
        const requestInfo = {
          subject : this.question.subject,
          content : this.question.content,
          file : this.impagePath
        }
        const response = await http.post('/student/message/addMessage', requestInfo);
        if (response.status === 200) {
          // 提交成功后跳转到问答列表页面
          this.$router.push('/qaT');
        } else {
          console.error('问题提交失败，状态码：', response.status);
          alert('问题提交失败，请检查网络连接或稍后重试');
        }
      } catch (error) {
        console.error('问题提交失败：', error);
        alert('问题提交出现异常，请检查网络连接或稍后重试');
      }
    }
  }
}
</script>

<style scoped>
.qa-add-page {
  background-color: #f0f9f9;
  min-height: 100vh;
}
.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}
.form-container {
  padding: 15px;
}
.image-preview {
  position: relative;
  width: 100px;
  height: 100px;
}
.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}
.image-preview .btn-close {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: white;
  border-radius: 50%;
  padding: 4px;
}
</style> 